$(document).ready(function(){
	var keditor = $('.keditor'), uploadJson = '/Home/Upload/index', filePostName = 'file';
    if(keditor.length > 0){
    	$.ajax({url:'/Public/Kindeditor/kindeditor.min.js', dataType:'script', cache:true}).done(function(){
    		KindEditor.basePath = '/Public/Kindeditor/';
  			KindEditor.loadStyle('/Public/Kindeditor/themes/default/default.css');
			var editor = KindEditor.create('.keditor', {uploadJson : uploadJson,filePostName : filePostName, resizeType : 1, filterMode: false, width : 672, height : 360, afterCreate: function(){this.sync();}, afterBlur: function(){this.sync();}});
		 });
    }

    //表单页操作 data-callback设置回调函数
    if($("#myform").length > 0){
		var err_num = 0;
    	$.ajax({url:'/Public/Admin/js/jquery.validate.min.js', dataType:'script', cache:true}).done(function(){
			jQuery.validator.addMethod("english", function(value, element) {
				var chrnum = /^([a-zA-Z]+)$/;
				return this.optional(element) || (chrnum.test(value));
			}, "只能输入字母");

			jQuery.validator.addMethod("chinese", function(value, element) {
				var chrnum = /^([\u4e00-\u9fa5]+)$/;
				return this.optional(element) || (chrnum.test(value));
			}, "只能输入中文");
			jQuery.validator.addMethod("xlActionk", function(value, element) {
				var _re_csrq = false;
				var _csrq = $("#csny").val();
				if(_csrq.length > 0){
					//_csrq = _csrq.replace((/-/gm) ,"/");
					_csrq = _csrq.split("-")
					_csrq_date = new Date(_csrq[0],parseInt(_csrq[1])-1,_csrq[2],"00","00","00");
					if(value === '本科'){
						_csrq_sjc = _csrq_date.getTime()/1000;
						_re_csrq = _csrq_sjc > 623174399?true:false;
					}else if(value === '研究生' ){
						_csrq_sjc = _csrq_date.getTime()/1000;
						_re_csrq = _csrq_sjc > 496943999?true:false;
					}
				}
				return this.optional(element) || _re_csrq;
			}, "学历为本科，其出生年月必须在1989年10月1日（含）以后；学历为研究生，其出生年月必须在1985年10月1日（含）以后");


			var form = $("#myform");
    		form.validate({
				rules: {
					lxdh: {
						required: true,
						digits:true,
						minlength: 7,
						maxlength: 11
					},
					sfzh: {
						required: true,
						minlength: 18,
						maxlength: 18
					},
					xm:{
						chinese:true,
						minlength: 2
					}
				},
				messages: {
					lxdh: {
						required: "请输入联系电话",
						number:	"联系电话只能是数字",
						minlength: "联系电话长度不能小于7位",
						maxlength: "联系电话长度不能大于11位"
					},
					sfzh: {
						required: "请输入身份证号",
						minlength: "身份证号长度只能是18位",
						maxlength: "身份证号长度只能是18位"
					},
					xm:{
						minlength: "姓名长度不能小于2位"
					}
				},
    			highlight:function(element) {
					$(element).closest('.required').addClass('red_error');
				},
    			unhighlight:function(element) {
					$(element).closest('.required').removeClass('red_error');
				},
    			errorPlacement:function(error, element) {
					if(err_num === 0){
						alert("您的信息填报有误，请根据报名表项目提示填写完整");
					}
					err_num++;
					error.appendTo(element.parent());
				},
    			submitHandler:function(){
					if(zxtb() === false){
						return false;
					}
    				waiting();
					$.post(form.attr('action'), form.serialize(), function(data){
						complete(); showInfo(data.info);
						setTimeout(function(){
							if(data.status == 1){
								var fun = form.data('callback'), url = data.url;
								if(fun != undefined){
									eval(fun+"("+JSON.stringify(data)+")");
								}else if(url != undefined){
									location.href = url;
								}else{
									form[0].reset();
									$('.keditor').length > 0 &&  KindEditor.instances[0].html("");
									$('.uploadify-div').length > 0 && $('.uploadify-div').remove();
								}
							}
						}, 1600);
					});
	    		}
	    	});
    	});
    }
    
    //Uploadify文件上传  data-name表单名称  data-type上传类型 data-multi是否多图上传 data-callback回调函数
    if($('.upload').length > 0){
    	$.ajax({url:'/Public/Admin/js/jquery.uploadify.min.js', dataType:'script', cache:true}).done(function(){
    		$('.upload').each(function(){
    			var obj = $(this), buttonText = obj.html(), id = obj.attr('id');
				console.log(obj.data);
				var name = obj.attr('name');
				name = name == undefined ? 'pic' : name;
				type = obj.data('type');
				fun = obj.data('callback'),
    			fileTypeExts = '*.jpg;*.jpeg;*.png;*.gif', multi = obj.data('multi') == true ? true : false;
    			$('#'+id).uploadify({
    				'uploader' : uploadJson, 'swf':'/Public/Admin/css/uploadify.swf', 'fileObjName':filePostName, 'buttonText':buttonText, 'fileSizeLimit':'2MB',
    				'queueSizeLimit':10, 'removeTimeout':1, 'multi':multi, 'fileTypeExts':fileTypeExts,
    				'onUploadSuccess' : function(file, data, response){
    					if (fun != undefined) {
    						eval(fun+"('"+data+"')");
    					}else{
    						data = $.parseJSON(data);
    						var div = $('#'+id).parent().find('.uploadify-div'), html = '<li>';
    						html += type == 'file' ? "<a href='"+data.url+"'>"+file.name.substr(0, file.name.lastIndexOf('.'))+"</a>" : "<img src='"+data.url+"' />";
    						html += "<input type='hidden' name='"+name+"' value='"+data.url+"' /><span style='color:blue;cursor:pointer;' class='uploadifyDel'>删除</span></li>";
    						multi && div.append(html) || div.html(html);
    					}
    				}
    			});
    		});
    	});
    }

    $('body').on('click', '.uploadifyDel', function(){
        $(this).parent().remove();
    });

    //快捷状态设置
    if($('.setStatus').length > 0){
    	$('.setStatus').click(function(){
    		var obj = $(this), url = obj.data('url'), status = obj.data('status'), html; waiting();
    		$.get(url, {status : status}, function(data){
    			complete(); showInfo(data.info);
    			if(data.status == 1){
    				obj.data('status', status == 1 ? 0 : 1);
                    html = status == 1 ? '禁用' : '启用';
    				if(status == 1){
    					obj.removeClass('btn-primary').addClass('btn-default').html(html);
    				}else{
    					obj.removeClass('btn-default').addClass('btn-primary').html(html);
    				}
    			}
    		});
    	});
    }
    //快捷修改排序
    if($('.setSort').length > 0){
    	$('.setSort').blur(function(){
    		var obj = $(this), sort = obj.val();
	    	if(!/^\d+$/.test(sort)){
	    		showInfo('只能输入整数哦');
	    	}else{
	    		waiting();
	    		$.get(obj.data('url'), {sort: sort}, function(data){
	    			complete(); showInfo(data.info);
	    		});
	    	}
	    });
    }
    //删除记录
    if($('.delBtn').length > 0){
    	$('.delBtn').click(function(){
    		var obj = $(this);
    		if(confirm("确定要删除吗？")){
    			waiting();
    			$.get(obj.data('url'), function(data){
    				complete(); showInfo(data.info);
    				data.status == 1 && obj.parents('tr').remove();
    			});
    		}
    	});
    }
    //关闭消息框
    $('body').on('click', '.prompt .close', function(){
    	$(this).parent().remove();
    });	
});

//消息提示框
function showInfo(info){
	var tmp = (Math.random() * 1000).toFixed(0);
	var html= '<div class="promp_text hide_' + tmp + '">' + info + '<div class="icon-remove close"></div></div>';
	if($('.prompt').length == 0){
		html = '<div class="prompt">' + html + '</div>';
		$("body").prepend(html);
	}else{
		$(".prompt").prepend(html);
	}
	$(".promp_text").animate({opacity: "1"}, 600);
	setTimeout('$(".hide_' + tmp + '").animate({opacity:"0"}, 1000,function(){$(".hide_' + tmp + '").remove();});', 1600);
}
//等待效果
function waiting(){
  $('body').append('<div class="load_effect"></div>');
}
//移除等待效果
function complete(){
  $('.load_effect').remove();
}